const mongoose = require('mongoose')

const UserSchema = new mongoose.Schema({
  username: { type: String, required: true, unique: true, trim: true },
  // 兼容明文与哈希两种存储方式（仅开发调试使用明文，生产请改为哈希）
  password: { type: String },
  passwordHash: { type: String },
  avatar: { type: String, default: 'https://picsum.photos/80' },
  createdAt: { type: Date, default: Date.now }
})

const User = mongoose.model('User', UserSchema)

// 微信用户模型 - 匹配 wechat_users 数据库结构
const WeChatUserSchema = new mongoose.Schema({
  openid: { type: String, required: true, unique: true },
  session_key: { type: String },
  nickname: { type: String },
  avatarUrl: { type: String },
  agreeProtocol: { type: Boolean, default: false },
  createdAt: { type: Date, default: Date.now },
  lastLoginAt: { type: Date, default: Date.now },
  status: { type: Boolean, default: true },
  phoneNumber: { type: String, default: '' },
  countryCode: { type: String, default: '+86' },
  purePhoneNumber: { type: String, default: '' }
})

const WeChatUser = mongoose.model('WeChatUser', WeChatUserSchema, 'wechat_users')

// 简单聊天模型：两人会话 + 消息数组
const MessageSchema = new mongoose.Schema({
  // 使用字符串以兼容虚拟用户ID（如 doctor_<id>）
  senderId: { type: String, required: true },
  content: { type: String },
  // 消息类型：text、voice、image
  type: { type: String, enum: ['text', 'voice', 'image'], default: 'text' },
  // 语音消息字段
  voiceUrl: { type: String },
  voiceDuration: { type: Number },
  voiceText: { type: String }, // 语音转文字结果
  // 图片消息字段
  imageUrl: { type: String },
  imageWidth: { type: Number },
  imageHeight: { type: Number },
  createdAt: { type: Date, default: Date.now },
  // 已读用户列表改为字符串，兼容虚拟ID
  readBy: [{ type: String }]
})

const ChatSchema = new mongoose.Schema({
  participants: [{ type: String, required: true }], // 改为String类型，支持虚拟用户ID
  messages: [MessageSchema],
  // 目标信息（用于医院/医生咨询）
  targetInfo: {
    type: { type: String }, // 'hospital' 或 'doctor'
    id: { type: String },
    name: { type: String }
  },
  updatedAt: { type: Date, default: Date.now }
})

ChatSchema.index({ participants: 1 })

const Chat = mongoose.model('Chat', ChatSchema)

module.exports = { User, Chat, WeChatUser }


